package com.nosweattechnet.server;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import android.util.Log;


//Performs all communication between the server and app
public class Communicator {
	//These values are stored in the Post, so that the php script can access them
	private ArrayList<NameValuePair> nameVPs;
	//Address of php script
	private static String httpadd="http://www.nosweattech.net/database.php";
	
	//Creates a Communicator and copies the values in the given array
	public Communicator(ArrayList<NameValuePair> nvp){
		nameVPs=new ArrayList<NameValuePair>();
		if(nvp!=null){
			for(NameValuePair n:nvp){
				nameVPs.add(new BasicNameValuePair(n.getName(),n.getValue()));
			}
		}
	}
	
	//Creats a Communicator with an empty array
	public Communicator(){
		nameVPs=new ArrayList<NameValuePair>();
	}
	
	//Adds a pair to the array
	public void addNameValuePair(NameValuePair nvp){
		nameVPs.add(nvp);
	}
	
	//Adds all pairs in the list to the stored array
	public void addNameValuePair(ArrayList<NameValuePair> nvps){
		nameVPs.addAll(nvps);
	}
	
	//Sends the request to the server, and retrieves an InputStream.  The InputStream is then converted by a separate function and a JSONArray is returned
	public JSONArray sendRequest() throws JSONException{
		InputStream is=null;
		try{
			HttpClient httpclient=new DefaultHttpClient();
			HttpPost httppost=new HttpPost(httpadd);
			httppost.setEntity(new UrlEncodedFormEntity(nameVPs));
			HttpResponse response=httpclient.execute(httppost);
			HttpEntity entity=response.getEntity();
			is=entity.getContent();
		}catch(Exception e){
			Log.e("log_tag","Error in http connection: "+e.toString());
		}
		JSONArray response=convertResponse(is);
		return response;
	}
	
	//Converts the InputStream to a JSONArray
	private JSONArray convertResponse(InputStream is) throws JSONException{
		if(is==null){
			return null;
		}
		String result="";
		try{
			BufferedReader reader=new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb=new StringBuilder();
			sb.append(reader.readLine()+"\n");
			String line="0";
			while((line=reader.readLine())!=null){
				sb.append(line+"\n");
			}
			is.close();
			result=sb.toString();
		}catch(Exception e){
			Log.e("log_tag","Error converting result: "+e.toString());
		}
		JSONArray jArray=new JSONArray(result);
		return jArray;
	}

}
